package com.ykzb.util;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

public class SNUtil
{
	private static Map<String, Object> map = Collections.synchronizedMap(new HashMap<String, Object>());
	private static String NUMBER = "number";
	private static String LASTSN = "LASTSN";
	private static Map<String, String> baseNoMap = new LinkedHashMap<String, String>();

	static
	{
		for (int i = 0; i <= 61; i++)
		{
			if (i <= 9)
			{
				baseNoMap.put(i + "", i + "");
			} else if (i > 9 && i <= 35)
			{
				baseNoMap.put(i + "", (char) (i + 55) + "");
			} else
			{
				baseNoMap.put(i + "", (char) (i + 61) + "");
			}
		}
	}

	public static synchronized String getSN()
	{
		if (map.get(NUMBER) == null)
		{
			map.put(NUMBER, new Integer(0));
		}
		String id = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		int number = ((Integer) map.get(NUMBER)).intValue();
		String no = "" + number;
		if (number == 9999)
		{
			number = 0;
		} else
		{
			number++;
		}
		map.put(NUMBER, new Integer(number));
		no = no.trim();
		int s = 4 - no.length();
		for (int i = 0; i < s; i++)
		{
			no = "0" + no;
		}
		id += no;
		return id;
	}

	public static synchronized String getSN(String prefix)
	{
		if (map.get(NUMBER) == null)
		{
			map.put(NUMBER, new Integer(0));
		}
		Date dt = new Date();
		String sn = prefix;
		sn += new SimpleDateFormat("yy").format(dt);
		sn += baseNoMap.get(YkzbDateTimeUtil.getMonth(dt) + "");
		sn += baseNoMap.get(YkzbDateTimeUtil.getDay(dt) + "");
		sn += baseNoMap.get(YkzbDateTimeUtil.getHour(dt) + "");
		long ms = YkzbDateTimeUtil.getMinute(dt) * 60 * 1000 + YkzbDateTimeUtil.getSecond(dt) * 1000 + YkzbDateTimeUtil.getMilliseconds(dt);
		int number = ((Integer) map.get(NUMBER)).intValue();
		if (number == 9999)
		{
			number = 0;
		} else
		{
			number++;
		}
		map.put(NUMBER, new Integer(number));
		String no = SNUtil.genNo(ms + number, 36);
		for (int i = 0; i < 4 - no.length(); i++)
		{
			no = "0" + no;
		}
		sn += no;
		Object obj = map.get(LASTSN);
		if (obj != null)
		{
			if (obj.equals(sn))
			{
				try
				{
					SNUtil.class.wait(1000);
				} catch (InterruptedException e)
				{
					e.printStackTrace();
				}
				return SNUtil.getSN(prefix);
			} else
			{
				map.put(LASTSN, sn);
			}
		}
		map.put(LASTSN, sn);
		return sn;
	}

	public static String genNo(long value, int m)
	{
		String no = "";
		while (value >= m)
		{
			no = baseNoMap.get((value % m) + "") + no;
			value = value / m;
		}
		no = baseNoMap.get(value + "") + no;
		return no;
	}

	public static String genNo(int size)
	{
		String value = "";
		Random ra = new Random();
		while (value.length() < size)
		{
			value += baseNoMap.get((ra.nextInt(36) + 1) + "");
		}
		return value;
	}

	public static void main(String[] args)
	{
		for (int i = 0; i < 10; i++)
		{
			//System.out.println(genNo(1));
		}
	}
}
